import 'package:flutter/material.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/widgets/common/xindong_app_bar.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

class XinDongWebYeMian extends StatefulWidget {
  // 常量接收参数
  final String title;
  final String url;

  // 构造函数
  const XinDongWebYeMian({Key? key, required this.title, required this.url}) : super(key: key);

  @override
  State<XinDongWebYeMian> createState() => _XinDongWebYeMianState();
}

class _XinDongWebYeMianState extends State<XinDongWebYeMian> {
  double progressValue = 0.0;
  late WebViewController _controller;

  @override
  void initState() {
    super.initState();

    try {
      // #docregion platform_features
      late final PlatformWebViewControllerCreationParams params;
      if (WebViewPlatform.instance is WebKitWebViewPlatform) {
        params = WebKitWebViewControllerCreationParams(
          allowsInlineMediaPlayback: true,
          mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
        );
      } else {
        params = const PlatformWebViewControllerCreationParams();
      }

      _controller = WebViewController.fromPlatformCreationParams(params);

      _controller
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..setBackgroundColor(DZColors.white)
        ..setNavigationDelegate(
          NavigationDelegate(
            onProgress: (int progress) {
              if (mounted) {
                setState(() {
                  progressValue = 1.0 * progress / 100;
                });
              }
            },
            onPageStarted: (String url) {
              mDebugPrint('YeMian started loading: $url');
            },
            onPageFinished: (String url) {
              mDebugPrint('YeMian finished loading: $url');
            },
            onWebResourceError: (WebResourceError error) {
              mDebugPrint('''
  YeMian resource error:
  code: ${error.errorCode}
  description: ${error.description}
  errorType: ${error.errorType}
  isForMainFrame: ${error.isForMainFrame}
          ''');
            },
            onNavigationRequest: (NavigationRequest request) async {
              if (request.url.contains("itunes.apple.com")) {
                bool result = await canLaunchUrlString(request.url);
                if (result) {
                  launchUrlString(request.url);
                  return NavigationDecision.prevent;
                }
              }
              return NavigationDecision.navigate;
            },
          ),
        )
        ..addJavaScriptChannel(
          'Toaster',
          onMessageReceived: (JavaScriptMessage message) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text(message.message)),
            );
          },
        );

      _controller.loadRequest(Uri.parse(widget.url));

      // #docregion platform_features
      if (_controller.platform is AndroidWebViewController) {
        AndroidWebViewController.enableDebugging(true);
        (_controller.platform as AndroidWebViewController).setMediaPlaybackRequiresUserGesture(false);
      }
      // #enddocregion platform_features
    } catch (e) {
      showToast(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (await _controller.canGoBack()) {
          _controller.goBack();
          return false;
        } else {
          return true;
        }
      },
      child: Scaffold(
        appBar: XinDongAppBar(widget.title),
        body: Stack(
          fit: StackFit.expand,
          children: [
            // web
            WebViewWidget(controller: _controller),

            // 进度条
            Positioned(
              left: 0,
              right: 0,
              top: 0,
              height: progressValue >= 1.0 ? 0.0 : 2.0,
              child: LinearProgressIndicator(
                backgroundColor: DZColors.mainLightColor,
                value: progressValue,
                valueColor: const AlwaysStoppedAnimation<Color>(DZColors.mainColor),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
